package com.qi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qi.commom.User;
import com.qi.result.Result;
import com.qi.service.LoginService;
import com.qi.utils.sendCode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.Duration;
import java.util.UUID;



@Controller
@Slf4j
@RequestMapping("/login")
public class LoginController {

    private final HttpServletRequest request;

    private final LoginService loginService;

    private final StringRedisTemplate redisTemplate;

    public LoginController(HttpServletRequest request, LoginService loginService, StringRedisTemplate redisTemplate) {
        this.request = request;
        this.loginService = loginService;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 去登录页
     */
    @RequestMapping("/goLogin")
    public String index(){
        return "login";
    }

    /**
     * 去注册用户
     */
    @RequestMapping("/register.html")
    public String register(){
        return "register";
    }

    /**
     * 登录方法
     *
     */
    @RequestMapping("/loginUser")
    @ResponseBody
    public int selectClazz (@RequestBody User user){
        log.info("接口功能：【{}】，请求地址：【{}】，请求方式：【{}】，请求参数：【{}】",
                "登录方法",request.getRequestURI(),request.getMethod(), JSON.toJSONString(user));

        User loginUser = loginService.loginUser(user);
        if (loginUser == null){
            return 1;
        }

        log.info("接口功能：【{}】，请求地址：【{}】，请求方式：【{}】，响应结果：【{}】",
                "登录方法",request.getRequestURI(),request.getMethod(), JSONObject.toJSONString(loginUser));

        // 将当前登录用户存入Redis当中去
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set("user", String.valueOf(loginUser));
        redisTemplate.expire("user",Duration.ofMinutes(30));
        return 2;
    }

    /**
     * 获取验证码
     */
    @PostMapping("/getCode")
    @ResponseBody
    public Result getCode (@RequestBody User user) throws Exception{
        log.info("接口功能：【{}】，请求地址：【{}】，请求方式：【{}】，请求参数：【{}】",
                "获取验证码",request.getRequestURI(),request.getMethod(), JSON.toJSONString(user));

        if (user.getPhone() == null){
            return Result.error(500,"手机号为空");
        }

        String code = UUID.randomUUID().toString().substring(0, 4);
        sendCode.sendMsg(code,user.getPhone());
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set(user.getPhone(),code);
        redisTemplate.expire(user.getPhone(), Duration.ofMinutes(10));

        log.info("接口功能：【{}】，请求地址：【{}】，请求方式：【{}】，响应结果：【{}】",
                "获取验证码",request.getRequestURI(),request.getMethod(),"发送成功");

        return Result.success(code,"发送成功！");
    }

    /**
     * 注册新账号
     */
    @RequestMapping("/insertUser")
    @ResponseBody
    public Result insertUser (@RequestBody User user){
        log.info("接口功能：【{}】，请求地址：【{}】，请求方式：【{}】，请求参数：【{}】",
                "注册新账号",request.getRequestURI(),request.getMethod(), JSON.toJSONString(user));

        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String oldCode = ops.get(user.getPhone());
        if (!user.getCode().equals(oldCode)){
            return Result.error("验证码错误!");
        }

        loginService.insertUser(user);

        log.info("接口功能：【{}】，请求地址：【{}】，请求方式：【{}】，响应结果：【{}】",
                "注册新账号",request.getRequestURI(),request.getMethod(),"注册成功");

        return Result.success(1,"注册成功!");
    }
}
